#include "math_morph.h"

pixel** erode(pixel** originalImage, EE* ee, int imageHeight, int imageWidth,
		int eeHeight, int eeWidth) {
	pixel** resultImage;
	int i, j, p, q, u, v;
	pixel s, t;

	resultImage = (pixel**)malloc(imageHeight * sizeof(pixel*));
	for (i = 0; i < imageHeight; i++) {
		resultImage[i] = (pixel*)malloc(imageWidth * sizeof(pixel));
	}

	for (i = 0; i < (imageHeight); i++) {
		for (j = 0; j < (imageWidth); j++) {
			s = t = 255;
			for (p = 0; p < (eeHeight); p++) {
				for (q = 0; q < (eeWidth); q++) {
					u = i + p - (eeHeight/2);
					v = j + q - (eeWidth/2);
					if ((u >= 0) && (u < imageHeight)) {
						if ((v >= 0) && (v < imageWidth)) {
							if ((255 - ee->Matrix[p][q]) > originalImage[u][v]) { //255-EE[p,q])>ImagePlus.GetPixel(Band,u,v
								t = 255 - ee->Matrix[p][q];
							} else {
								t = originalImage[u][v];
							}
						}
					}
					if (t < s) {
						s = t;
					}
				}
				resultImage[i][j] = s;
			}
		}
	}

	return resultImage;
}

pixel** dilate(pixel** originalImage, EE* ee, int imageHeight, int imageWidth,
		int eeHeight, int eeWidth) {
	pixel** resultImage;
	int i, j, p, q, u, v;
	pixel s, t;

	resultImage = (pixel**)malloc(imageHeight * sizeof(pixel*));
	for (i = 0; i < imageHeight; i++) {
		resultImage[i] = (pixel*)malloc(imageWidth * sizeof(pixel));
	}

	for (i = 0; i < (imageHeight); i++) {
		for (j = 0; j < (imageWidth); j++) {
			s = t = 0;
			for (p = 0; p < (eeHeight); p++) {
				for (q = 0; q < (eeWidth); q++) {
					u = i + p - (eeHeight/2);
					v = j + q - (eeWidth/2);
					if ((u >= 0) && (u < imageHeight)) {
						if ((v >= 0) && (v < imageWidth)) {
							if ((ee->Matrix[p][q]) < originalImage[u][v]) { //255-EE[p,q])>ImagePlus.GetPixel(Band,u,v
								t = ee->Matrix[p][q];
							} else {
								t = originalImage[u][v];
							}
						}
					}
					if (t > s) {
						s = t;
					}
				}
				resultImage[i][j] = s;
			}
		}
	}

	return resultImage;
}
